<?php
//https://www.yuque.com/dalianshouchuangkejishangfei/nscaqs/iktxgz
namespace jy_zwechat;
defined('BY_JYA') or exit('error');
class pay extends \plugin{
    public function __construct($setting=array()){
        parent::__construct('jy_zwechat');
        $setting=uni_setting('pay');
        if(!$setting['zwechat_mid'] || !$setting['zwechat_key'] || !$setting['zwechat_tid']){
            exi('商户编号，终端号，接口密钥，都必须填写','error');
        }
        if($_SESSION['auth_wxid']){
            $auth_appid=pdo_getcolumn('core_account_wechat',array('id'=>$_SESSION['auth_wxid']),'appid');
        }
        $wechat_appid=$auth_appid?:$setting['wechat_appid'];
        if(!$wechat_appid){
            $wechat_appid=pdo_getcolumn('core_account_wechat',array('uniacid'=>$_SESSION['uniacid'],'isdefault'=>1),'appid');
            if(!$wechat_appid){
                $wechat_appid=pdo_getcolumn('core_account_wechat',array('uniacid'=>$_SESSION['uniacid']),'appid');
            }
        }
        $this->config=array(
            'sub_appid'=>$wechat_appid,
            'm_no'=>$setting['zwechat_mid'],
            'terminal_id'=>$setting['zwechat_tid'],
			'zwechat_key'=>$setting['zwechat_key'],
        );
    }
    //创建订单
    public function create($pay_log,$paytype='',$wxappid=''){
        # 支付设置
        if($paytype=='wechat'){
            if($_SESSION['container']=='wechat'){
                $pay_mode=1;
                $pay_type=4;
                if(!$this->config['sub_appid']) {
                    exi('未绑定微信公众号，不能使用微信支付！', 'error');
                }
            }elseif($_SESSION['container']=='wxapp'){
                $this->config['sub_appid']=$wxappid?:$this->config['sub_appid'];
                $pay_mode=1;
                $pay_type=2;
            }else{
				$pay_mode=1;
                $pay_type=9;
				if(!$this->config['sub_appid']) {
                    exi('未绑定微信公众号，不能使用微信支付！', 'error');
                }
            }
			$pay_type=4;
        }
        if($paytype=='alipay'){
             $pay_mode=2;
             $pay_type=2;
        }
        $scene_info=array(
            'h5_info'=>array('type'=>'Android','app_name'=>$_SESSION['account']['title']?:'未设置','package_name'=>'com.tencent.tmgp.sgame'),
        );
        $payment_params = array(
            'm_no'=>$this->config['m_no'],
            'terminal_id'=>$this->config['terminal_id'],
			'pay_mode'=>$pay_mode,
			'pay_type'=>$pay_type,
			'amount'=>$pay_log['fee'],
			'account_type'=>1,
			//'sub_appid'=>$this->config['sub_appid'],
            'order_no'=> $pay_log['tid']?:$pay_log['ordersn'],
			'scene_info'=>ijson_encode($scene_info),
            'body'=>$pay_log['title'],
            'notify_url'=>$pay_log['notify_url']?:SITEROOT .'addons/jy_zwechat/notify.php',
        );
		if($pay_type==2 || $pay_log['openid'] || $_SESSION['openid']){
			$payment_params['sub_openid']=$pay_log['openid'];
		}
        $res=$this->request('http://pay.zwechat.com/api.php/Gateway/pay',$payment_params);
        //file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 支付记录:" . json_encode($payment_params)."\r\n", FILE_APPEND);
        //file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 返回信息:" . ijson_encode($res)."\r\n", FILE_APPEND);
		if($res['return_code']!='success'){
			exi('支付失败，失败原因:'.$res['return_msg'],'error');
		}
        $package=array(
                'appId'=>$res['appId'],
                'timeStamp'=>$res['timeStamp'],
                'package'=>$res['package'],
                'signType'=>$res['signType'],
                'nonceStr'=>$res['nonceStr'],
				'paySign'=>$res['paySign'],
				'order_no'=>$res['order_no'],
				'order_sn'=>$res['order_sn'],
        );
        return $res['pay_url'];
    }
	public function request($url,$post=null,$continue=true,$direct=false,$return_error=false,$isjson=false,$isrequest=false){
		$sign=$this->getSign($post);
	    $post['sign']=$sign;
		$post=ijson_encode($post);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " request记录:" . $post."\r\n", FILE_APPEND);
		$rurl=$url;
		if($isjson){
			$headers = array('Content-Type' => 'application/json');
			$result=cfc('http')->ihttp_json($rurl,$post);
		}elseif($isrequest){
			$result=cfc('http')->ihttp_request($rurl,$post);
		}elseif($post){
			$result=cfc('http')->ihttp_post($rurl,$post);
		}else{
			$result=cfc('http')->ihttp_get($rurl);
		}
		if(is_error($result)){			
			$message="支付错误, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if(($data['errcode']=='40001' || $data['errcode']=='42001') && $continue){
			$this->getAccessToken(true);
			$data=$this->request($url,$post,false,$direct,$return_error);
			return $data;
		}
		
		if($data['errcode']){
			$message=$this->error_code($data['errcode']).' '.$data['errmsg'].' '.$data['errcode'];
			if($return_error || $_SESSION['this']=='custom'){
				//return error($message);
			}else{
				//exi($message,'error');
			}
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
			$message='支付错误，以下为原始数据：'.$result['content'];
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $data;
	}
	/**
     * 作用：格式化参数
     */
    public function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort ( $paraMap );
        foreach ( $paraMap as $k => $v ) {
            if ($urlencode) {
                $v = urlencode ( $v );
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen ( $buff ) > 0) {
            $reqPar = substr ( $buff, 0, strlen ( $buff ) - 1 );
        }
        return $reqPar;
    }
    /**
     * 作用：生成签名
     */
    public function getSign($Obj, $key='') {
		$key=$this->config['zwechat_key'];
        foreach ( $Obj as $k => $v ) {
            $Parameters [$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort ( $Parameters );
        $String = $this->formatBizQueryParaMap ($Parameters, false);
        //签名步骤二：MD5加密
        $String = md5 ( $String . $key );
        //签名步骤三：所有字符转为大写
        $result_ = strtoupper ( $String );
        return $result_;
    }
}